"use client"
import { useMoralis, useMoralisWeb3Api } from "react-moralis"
import { useEffect, useState } from "react"
import { ethers } from "ethers"

export function ManualHeader() {
    const { enableWeb3, isWeb3Enabled, account, Moralis,
         deactivateWeb3, isWeb3EnableLoading } = useMoralis()
    // const web3Api = useMoralisWeb3Api()
    const [balance, setBalance] = useState("0")

    useEffect(() => {
        console.log("isWeb3Enabled changed", isWeb3Enabled)
        if (
            !isWeb3Enabled &&
            typeof window !== "undefined" &&
            window.localStorage.getItem("connected") // check if key(connected) exists
        ) {
            enableWeb3()
        }
    }, [isWeb3Enabled])
    // no array, run on every render
    // empty array, run once
    // dependency array, run when the stuff in it changesan

    useEffect(() => {
        Moralis.onAccountChanged((newAccount) => {
            console.log(`Account changed to ${newAccount}`)
            if (newAccount == null) {
                window.localStorage.removeItem("connected")
                deactivateWeb3()
                console.log("Null account found")
            }
        })
    }, [])

    useEffect(() => {
        async function fetchBalance() {
            // if (account) {
            //     // 获取余额用 Moralis 的 Web3API，需要依赖 Moralis 后端服务, 要有 apiKey, 有些版本还存在兼容性问题
            //     const result = await web3Api.account.getNativeBalance({ 
            //         chain: "0x7a69",  // 本地链用链ID 31337 的十六进制 "0x7a69"
            //         address: account })
            //     // 返回的是 Wei，需要转换为 ETH
            //     const balanceInEth = Moralis.Units.FromWei(result.balance)
            //     setBalance(balanceInEth)
            // }

            // 另一种获取余额的方式是直接用 ethers.js
            if (account && typeof window !== "undefined") {
                const provider = new ethers.providers.Web3Provider(window.ethereum)
                const balanceBigInt = await provider.getBalance(account)
                const balanceInEth = ethers.utils.formatEther(balanceBigInt)
                setBalance(balanceInEth)
            }
        }
        fetchBalance()
    }, [account])

    return (
        <nav className="p-5 border-b-2">
            <ul className="">
                <li className="flex flex-row">
                    {account ? (
                        <>
                            <div className="ml-auto py-2 px-4">
                                Connected to {account.slice(0, 6)}...
                                {account.slice(account.length - 4)}
                            </div>
                            <div className="ml-auto py-2 px-4">
                                Balance: {balance} ETH
                            </div>
                        </>
                    ) : (
                        <button
                            onClick={async () => {
                                // await walletModal.connect()
                                const ret = await enableWeb3()
                                if (typeof ret !== "undefined") {
                                    // depends on what button they picked
                                    if (typeof window !== "undefined") {
                                        window.localStorage.setItem("connected", "injected")
                                        // window.localStorage.setItem("connected", "walletconnect")
                                    }
                                }
                            }}
                            disabled={isWeb3EnableLoading}
                            className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded ml-auto"
                        >
                            Connect
                        </button>
                    )}
                </li>
            </ul>
        </nav>
    )
}
